import React, { useState, useEffect } from 'react';

interface NameModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (name: string) => void;
  error: string | null;
}

const NameModal: React.FC<NameModalProps> = ({ isOpen, onClose, onSubmit, error }) => {
  const [name, setName] = useState('');

  useEffect(() => {
    if (isOpen) {
      setName('');
    }
  }, [isOpen]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(name);
  };

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50 animate-fade-in-fast" onClick={onClose}>
      <div className="bg-slate-800 rounded-xl shadow-2xl p-6 sm:p-8 w-full max-w-md m-4 border border-slate-700" onClick={(e) => e.stopPropagation()}>
        <h2 className="text-2xl font-bold text-white mb-4">请输入队长名称</h2>
        <p className="text-slate-400 mb-6">输入您的名称以分配到小组。每位队长只能抽签一次。</p>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="例如：林丹"
            autoFocus
            className="w-full px-4 py-3 bg-slate-900 border-2 border-slate-600 rounded-md text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
          />
          {error && <p className="text-red-400 mt-3 text-sm">{error}</p>}
          <div className="flex justify-end gap-4 mt-8">
            <button
              type="button"
              onClick={onClose}
              className="px-6 py-2 rounded-md text-slate-300 bg-slate-700 hover:bg-slate-600 transition font-semibold"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={!name.trim()}
              className="px-6 py-2 rounded-md text-white font-semibold bg-blue-600 hover:bg-blue-700 transition disabled:opacity-50"
            >
              确认并抽签
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default NameModal;